<!DOCTYPE html>
<html>
	<head>
		<title>Google Maps Example</title>
		<script
			src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDpyOB_95_C3BpdyhYJs7c53Z-0O6eS0GM&callback=initMap&libraries=places&v=weekly"
			defer async></script>
		<style>
			#map {
				height: 100%;
				width: 100%;
			}

			html,
			body {
				height: 100%;
				margin: 0;
				padding: 0;
			}

			#navigation-instructions {
				position: absolute;
				top: 10px;
				left: 10px;
				max-width: 40vw;
				max-height: 500px;
				overflow: auto;
				background: white;
				/* padding: 10px; */
				z-index: 1000;
				margin-bottom: 10px;
			}
		</style>
	</head>
	<!-- uni 的 SDK -->
	<!-- 需要把 uni.webview.1.5.6.js 下载到自己的服务器 -->
	<!-- <script type="text/javascript" src="https://gitcode.net/dcloud/uni-app/-/raw/dev/dist/uni.webview.1.5.6.js"> -->
	<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js" defer
		async>
	</script>
	<script src="./common.js"></script>
	<script type="text/javascript">
		// 待触发 `UniAppJSBridgeReady` 事件后，即可调用 uni 的 API。
		document.addEventListener('UniAppJSBridgeReady', function() {
			uni.postMessage({
				data: {
					action: 'message'
				}
			});
			uni.getEnv(function(res) {
				console.log('当前环境：' + JSON.stringify(res));
			});

			// 创建 WebSocket 连接
			const socket = new WebSocket('wss://www.rightaway.icu/ws/');
			// 连接打开时的处理逻辑
			socket.addEventListener('open', (event) => {
				console.log('WebSocket connection opened.');
				// 可以在这里发送初始消息给服务器
				// socket.send('Hello, server!');
			});


			// return


			// 接收到消息时的处理逻辑
			socket.addEventListener('message', async (event) => {
				let res = JSON.parse(event.data)
				if (res.event_code == 100) {
					const loginResponse = await fetch("https://web.delivery-asap.com/api/user/login", {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
						},
						body: JSON.stringify({
							account: "0928127288",
							password: "A123456a",
							group_id: "3",
						}),
					});
					const loginData = await loginResponse.json();
					console.log("loginData_____", JSON.stringify(loginData))
					var data = new FormData();
					data.append("uid", loginData.data.userinfo.id);
					data.append("client_id", res.data.client_id);
					const bindResponse = await fetch("https://www.rightaway.icu/api/user/bind_uid", {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
							"Token": loginData.data.userinfo.token,
							"User-Agent": "Apifox/1.0.0 (https://apifox.com)"
						},
						body: data
					})
					const bindData = await bindResponse.json()
				} else {
					console.log("MESSAGES---ELSE", JSON.stringify(res))
				}
				// 可以在这里处理接收到的消息
				// console.log('Received message:FINISH-----', JSON.stringify(res));
			});

			// 定义重连函数
			async function reconnect(attempt = 1) {
				if (attempt > 5) {
					console.error('Reconnection attempts exceeded.');
					return;
				}
				return new Promise((resolve, reject) => {
					// 在这里实现重连逻辑
					// 例如，等待一段时间后重新创建 WebSocket 连接
					setTimeout(() => {
						// 重新创建 WebSocket 连接
						const newSocket = new WebSocket('wss://www.rightaway.icu/ws/');
						newSocket.addEventListener('open', (event) => {
							resolve();
						});
						newSocket.addEventListener('error', (event) => {
							reject(event);
						});
					}, 5000); // 等待5秒后重连
				}).then(() => {
					console.log('Reconnected successfully.');
				}).catch((error) => {
					console.error('Reconnection failed:', error);
					reconnect(attempt + 1); // 递归调用重连函数，增加尝试次数
				});
			}

			// 发送心跳包
			let sendTimer = setInterval(() => {
				if (socket.readyState === WebSocket.OPEN) {
					socket.send('{"event":"heart"}');
					console.log("SEND______________MESSAGE")
				}
			}, 30000);


			// 连接关闭时的处理逻辑
			socket.addEventListener('close', (event) => {
				console.log('WebSocket connection closed.');
				// 可以在这里处理连接关闭后的逻辑
				sendTimer = null
			});

			// 发生错误时的处理逻辑
			socket.addEventListener('error', (event) => {
				console.error('WebSocket error:', event);
				// 可以在这里处理错误
				// 尝试重新连接
				try {
					reconnect();
					console.log('Reconnected successfully————————.');
				} catch (error) {
					console.error('Reconnection failed:—————————', error);
					sendTimer = null
				}
			});


		});
	</script>
	<body>
		<div id="map"></div>
		<script>
			var map;
			let directionsService;
			let directionsRenderer;
			var urlParams = new URLSearchParams(window.location.search);

			let start = JSON.parse(urlParams.get('start'))
			let end = JSON.parse(urlParams.get('end'))
			// console.log(start.lat,start.lng)
			async function initMap() {
				let pos = await getLocation()
				// const myLatlng = {
				// 	lat: pos.lat,
				// 	lng: pos.lng
				// };
				console.log("initMap----:	")
				const myLatlng = {
					lat: start.lat,
					lng: start.lng
				};
				map = new google.maps.Map(document.getElementById("map"), {
					zoom: 4,
					center: myLatlng,
					mapId: "DEMO_MAP_ID",
				});

				directionsService = new google.maps.DirectionsService();
				directionsRenderer = new google.maps.DirectionsRenderer();
				directionsRenderer.setMap(map);

				// 示例：规划从北京到上海的路线
				// planRoute({
				// 	lat: 35.412026,
				// 	lng: 116.581137,
				// }, {
				// 	lat: 35.494119,
				// 	lng: 117.198287
				// });
				// let start1 ={
				// 	lat: start.lat,
				// 	lng: start.lng,
				// }
				// let end1 ={
				// 	lat: end.lat,
				// 	lng: end.lng
				// }
				setTimeout(() => {
					planRoute(start, end)
				}, 0)
			}

			let selfMarker = null; // 用于存储 type 为 "self" 的标记

			function addMarks(lat, lng, type) {
				console.log("lat:__________", lat, lng)
				var wgs84togcj02 = coordtransform.wgs84togcj02(lng, lat);
				console.log("wgs84togcj02:__________", wgs84togcj02[0])
				// 创建新的标记
				var marker = new google.maps.Marker({
					position: new google.maps.LatLng(wgs84togcj02[1], wgs84togcj02[0]),
					type: type // 传递 type 值
				});
				// 清除 type 为 "self" 的标记
				if (selfMarker) {
					selfMarker.setMap(null);
				}
				// 如果新的标记类型是 "self"，更新 selfMarker
				if (type === "self") {
					selfMarker = marker;
				}
				// 将新标记添加到地图
				marker.setMap(map);

				// 打印标记对象到控制台
				console.log("marker:", marker);
			}

			function planRoute(start, end) {
				// console.log(start.lng, end)
				directionsService.route({
					origin: start,
					destination: end,
					travelMode: google.maps.TravelMode.DRIVING,
				}, (response, status) => {
					if (status === "OK") {
						directionsRenderer.setDirections(response);
						console.log("response.routes[0].legs[0]", response.routes[0].legs[0].start_location.lat(),
							"start:", start.lat)
						map.setCenter(response.routes[0].legs[0].start_location);
						map.setZoom(10);
						displayNavigationInstructions(response.routes[0].legs[0])
					} else {
						window.alert("Directions request failed due to " + status);
					}
				});
			}

			function getLocation() {
				return new Promise((resolve) => {
					if (navigator.geolocation) {
						navigator.geolocation.getCurrentPosition((position) => {
							const latitude = position.coords.latitude;
							const longitude = position.coords.longitude;
							// console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
							resolve({
								lat: latitude,
								lng: longitude
							});
						});
					} else {
						console.log(`Geolocation is not supported by this browser.`);
						resolve(null);
					}
				});
			}

			function displayNavigationInstructions(leg) {
				const instructions = leg.steps.map(step => step.instructions).join("\n");
				document.getElementById("navigation-instructions").innerHTML = `Navigation Instructions:\n${instructions}`;
				let text = document.getElementById("navigation-instructions").innerText
				let arr = text.split("，")
				let str = ''
				for (let i = 0; i < arr.length; i++) {
					console.log("instructions-----", arr[i])
					str += arr[i] + '\n'
				}
				document.getElementById("navigation-instructions").innerHTML = str
				// 动态创建一个音频标签并播放
				const audio = document.createElement("audio")
				// audio.src=`http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&per=3&spd=5&text=${text}`
				let src = `https://fanyi.baidu.com/gettts?lan=zh&text=${encodeURIComponent(text)}&spd=5`
				console.log('src: ', src);
				// audio.src =`https://fanyi.baidu.com/gettts?lan=zh&text=${encodeURIComponent(text)}&spd=5`
				audio.src =`https://fanyi.baidu.com/gettts?lan=zh&text=%E5%A6%82%E6%9E%9C%E4%BD%A0%E5%90%8C%E6%97%B6%E5%90%83%E4%BA%86%E4%B8%80%E5%9D%97%E9%A6%99%E8%95%89%E5%92%8C%E4%B8%80%E5%9D%97%E6%A9%99%E5%AD%90%EF%BC%8C%E4%BC%9A%E5%8F%91%E7%94%9F%E4%BB%80%E4%B9%88%EF%BC%9F&spd=5`
				audio.play()
				audio.addEventListener('ended', function() {
					console.log('Audio has finished playing.');
					document.getElementById("navigation-instructions").style.display = 'none'
					// 你可以在这里添加其他操作，比如播放下一个音频文件
				});
			}
			// document.getElementById('postMessage').addEventListener('click', displayNavigationInstructions);

			// 每隔30秒获取一次定位信息
			setInterval(() => {
				getLocation().then((position) => {
					if (position) {
						// console.log(`Latitude: ${position.lat}, Longitude: ${position.lng}`);
						// 在这里处理位置信息
						// planRoute(position, end)
						addMarks(position.lat, position.lng, 'self')

					} else {
						console.log('Geolocation is not supported by this browser.');
					}
				});
			}, 10000);



			// 初始化获取一次定位信息
			getLocation().then((position) => {
				if (position) {
					// console.log(`Latitude: ${position.lat}, Longitude: ${position.lng}`);
					// planRoute(position, end)
				} else {
					console.log('Geolocation is not supported by this browser.');
				}
			});
		</script>
		<div id="navigation-instructions">
			<p class="desc">网页向应用发送消息，注意：小程序端应用会在此页面后退时接收到消息。</p>
			<div class="btn-list">
				<button class="btn btn-red" type="button" id="postMessage">postMessage</button>
			</div>
		</div>
	</body>
	<script>



	</script>
</html>